package com.example.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * 验证码生成Servlet
 */
@WebServlet("/verifyCode")
public class VerifyCodeServlet extends HttpServlet {

    private static final int WIDTH = 120;      // 验证码图片宽度
    private static final int HEIGHT = 40;      // 验证码图片高度
    private static final int CODE_LENGTH = 4;  // 验证码长度

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        // 创建图片缓冲区
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();

        // 设置背景色
        g.setColor(new Color(240, 240, 240));
        g.fillRect(0, 0, WIDTH, HEIGHT);

        // 生成随机验证码
        String code = generateCode();
        
        // 将验证码存入session
        HttpSession session = request.getSession();
        session.setAttribute("verifyCode", code);
        session.setAttribute("verifyCodeTime", System.currentTimeMillis());

        // 绘制验证码
        drawCode(g, code);

        // 绘制干扰线
        drawInterferenceLines(g);

        // 释放图形资源
        g.dispose();

        // 设置响应头，禁止缓存
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        // 输出图片
        ImageIO.write(image, "JPEG", response.getOutputStream());
    }

    /**
     * 生成随机验证码
     */
    private String generateCode() {
        String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        
        for (int i = 0; i < CODE_LENGTH; i++) {
            code.append(chars.charAt(random.nextInt(chars.length())));
        }
        
        return code.toString();
    }

    /**
     * 绘制验证码
     */
    private void drawCode(Graphics2D g, String code) {
        Random random = new Random();
        
        // 设置字体
        Font[] fonts = {
            new Font("Arial", Font.BOLD, 28),
            new Font("Times New Roman", Font.BOLD, 28),
            new Font("Courier New", Font.BOLD, 28)
        };

        for (int i = 0; i < code.length(); i++) {
            // 随机颜色
            g.setColor(new Color(random.nextInt(100), random.nextInt(100), random.nextInt(100)));
            
            // 随机字体
            g.setFont(fonts[random.nextInt(fonts.length)]);
            
            // 随机旋转角度
            int degree = random.nextInt(30) - 15;
            
            // 计算字符位置
            int x = 20 + i * 25;
            int y = 28;
            
            // 旋转并绘制字符
            g.rotate(Math.toRadians(degree), x, y);
            g.drawString(String.valueOf(code.charAt(i)), x, y);
            g.rotate(-Math.toRadians(degree), x, y);
        }
    }

    /**
     * 绘制干扰线
     */
    private void drawInterferenceLines(Graphics2D g) {
        Random random = new Random();
        
        // 绘制10条干扰线
        for (int i = 0; i < 10; i++) {
            int x1 = random.nextInt(WIDTH);
            int y1 = random.nextInt(HEIGHT);
            int x2 = random.nextInt(WIDTH);
            int y2 = random.nextInt(HEIGHT);
            
            g.setColor(new Color(random.nextInt(200), random.nextInt(200), random.nextInt(200)));
            g.drawLine(x1, y1, x2, y2);
        }
        
        // 绘制噪点
        for (int i = 0; i < 50; i++) {
            int x = random.nextInt(WIDTH);
            int y = random.nextInt(HEIGHT);
            g.setColor(new Color(random.nextInt(200), random.nextInt(200), random.nextInt(200)));
            g.fillOval(x, y, 2, 2);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}

